SOAP12_ENV = """<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body>%s</soapenv:Body></soapenv:Envelope>"""

SOAP11_ENV = """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body>%s</soapenv:Body></soapenv:Envelope>"""

SOAP11_FAULT = """<?xml version="1.0"?>
<soapenv:Envelope
  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
       <soapenv:Fault>
           <faultcode>%(faultcode)s</faultcode>
           <faultstring>%(faultstring)s</faultstring>
           <faultactor>%(faultactor)s</faultactor>
           <detail>
            %(detail)s
           </detail>
       </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>"""

SOAP12_FAULT = """<?xml version="1.0"?>
<soapenv:Envelope
  xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Body>
       <soapenv:Fault>
           <faultcode>%(faultcode)s</faultcode>
           <faultstring>%(faultstring)s</faultstring>
           <faultactor>%(faultactor)s</faultactor>
           <detail>
            %(detail)s
           </detail>
       </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>"""

CDATA = "<![CDATA[%s]]>"

def make_fault(faultstring, faultcode="Server", detail="", 
               faultactor="", soap_version="1.1"):
    """Returns a soap fault wrapped in an envelope as a string.  If detail
    is specified and does not start with an '<' it will be wrapped in
    both an errorMessage tag and a CDATA section"""
    if detail and not detail.startswith("<"):
        detail = "<errorMessage>%s</errorMessage>" % (CDATA % detail)
    if soap_version == "1.1":
        return SOAP11_FAULT % locals()
    elif soap_version == "1.2":
        return SOAP12_FAULT % locals()
    else:
        raise RuntimeError("SOAP Version (%s) Unsupported.  Use 1.1 or 1.2"
                            % soap_version)

def envelope(body, soap_version="1.1"):
    """Wraps the provided body in a default SOAP envelope"""
    if soap_version == "1.1":
        return SOAP11_ENV % body
    elif soap_version == "1.2":
        return SOAP12_ENV % body
    else:
        raise RuntimeError("SOAP Version (%s) Unsupported.  Use 1.1 or 1.2"
                            % soap_version)
